<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-6-8
 * Time: 16:29
 */

namespace app\api\controller;

use app\common\constant\CommonConstant;
use app\common\model\EngineerVoice;
use app\common\model\HandCard;
use think\Db;
use think\Exception;
use app\common\model\ProductOrder;
use app\common\service\FeiEPrintService;
use app\common\model\Room as RoomModel;

/**
 * 前台首页控制器
 * @package app\index\controller
 */
class Room extends Auth
{
    public $noNeedLogin = [];

    /**
     * 获取房间类型
     * @return array
     */
    public function getRoomType()
    {
        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $data = Db::name('qt_room_type')
                ->field('id,name')
                ->where(['store_id' => $userInfo['store_id'], 'status' => '1'])
                ->order('sort asc')
                ->select();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     *获取房间状态
     * @return array
     */
    public function getRoomStatus()
    {
        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $data = Db::name('qt_room_status')
                ->field('id,name')
                ->where(['store_id' => $userInfo['store_id'], 'status' => '1'])
                ->order('sort asc')
                ->select();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     *开房间
     */
    public function open()
    {
        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $getData = $this->request->post();
            if (empty($getData['room_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $data = Db::name('qt_room')
                ->field('id,name,status_id')
                ->where(['id' => $getData['room_id'], 'store_id' => $userInfo['store_id'], 'status_id' => '1'])
                ->find();
            if (empty($data) || $data['status_id'] != '1') {
                $this->result('房间状态有问题', '', 204);
            }
            try {
                Db::startTrans();
                //修改房间状态
                Db::name('qt_room')->where(['id' => $getData['room_id']])->update(['status_id' => '10']);
                RoomModel::openLog($getData['room_id'], $userInfo['id']);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('开房失败', '', 204);
            }
            $this->result('开房成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 房间备注
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remarks()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['room_id'])) {
                $this->result('缺少房间号', '', 204);
            }
            $update = Db::name('qt_room')->where(['id' => $getData['room_id']])->update(['content' => $getData['content']]);
            if ($update !== false) {
                $this->result('备注成功', '', 200);
            }
            $this->result('备注失败，请稍后再试', '', 204);
        }
    }


    /**
     * 房间预约
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function appointment()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!empty($getData['room_id'])) {
                $roomRes = Db::name('qt_room')->where('id', $getData['room_id'])->find();
            } else {
                $roomRes['status_id'] = '';
            }
            if (empty($getData['time'])) {
                $getData['time'] = time();
            } else {
                $getData['time'] = strtotime($getData['time']);
            }
            $getData['created_time'] = time();
            $getData['creater'] = $this->userInfo['id'];
            try {
                Db::startTrans();
                //修改订单状态
                $appointmentId = Db::name('qt_room_appointment')->insertGetId($getData);
                if ($roomRes['status_id'] == '1') {
                    Db::name('qt_room')->where('id', $getData['room_id'])->update(['status_id' => '9']);
                }
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('预约失败', '', 204);
            }
            //插入预约播报
            EngineerVoice::sendAppointmentVoice($appointmentId,'1');
            $this->result('预约成功', '', 200);
        }
    }

    /**
     * 取消预约
     */
    public function del_appointment()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['id'])) {
                $this->result('缺少预约信息', '', 204);
            }
            $find = Db::name('qt_room_appointment')->where('id', $getData['id'])->find();
            $userStatus = Db::name('qt_users')->where('id', $find['engineer_id'])->value('work_status');
            if (empty($find)) {
                $this->result('未找到房间预约信息', '', 204);
            }
            try {
                Db::startTrans();
                //修改订单状态
                Db::name('qt_room_appointment')->where('id', $getData['id'])->update(['status' => '3']);
                Db::name('qt_room')->where('id', $find['room_id'])->update(['status_id' => '1']);
                if($userStatus == '3'){
                    Db::name('qt_users')->where('id', $find['engineer_id'])->update(['work_status' => '1']);
                }
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('取消失败', '', 204);
            }
            //插入预约播报
            EngineerVoice::sendAppointmentVoice($getData['id'],'2');
            $this->result('取消成功', '', 200);
        }
    }


    /**
     * 确认到达预约
     */
    public function confirm_appointment()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['id'])) {
                $this->result('缺少预约信息', '', 204);
            }
            $find = Db::name('qt_room_appointment')->where('id', $getData['id'])->find();
            //技师不是空闲状态无法确认到达
            if (!empty($find['engineer_id'])) {
                $engineerStatus = Db::name('qt_users')->where(['id' => $find['engineer_id']])->value('work_status');
                if (in_array($engineerStatus,['1','3']) == false) {
                    $this->result('技师不是空闲状态', '', 204);
                }
            }
            //如果预定的房间和到达房间一致
            $update['room_id'] = $getData['room_id'];
            if(isset($getData['is_call']) && !empty($getData['is_call'])){
                $isCall = $getData['is_call'];
            }else{
                $isCall = $find['is_call'];
            }
            if ($isCall == '1') {
                $orderType = '2';
            } else {
                $orderType = '3';
            }
            //如果存在项目的话给技师添加项目
            if (!empty($getData['project_id']) || !empty($find['project_id'])) {
                $update['project_id'] = $getData['project_id'];
                $projectRes = Db::name('qt_project')->where('id', $getData['project_id'])->find();
                if(isset($getData['engineer_id']) && !empty($getData['engineer_id'])){
                    $engineerWorkStatus = Db::name('qt_users')->where(['id'=>$getData['engineer_id']])->value('work_status');
                    if(in_array($engineerWorkStatus,['1','3']) == false){
                        $this->result('技师不是空闲状态', '', 204);
                    }
                    $engineerId = $getData['engineer_id'];
                }else{
                    $engineerId = $find['engineer_id'];
                }
                if(isset($getData['room_id']) && !empty($getData['room_id'])){
                    $roomId = $getData['room_id'];
                }else{
                    $roomId = $find['room_id'];
                }
                try {
                    //判断当前房间是否有未结账订单
                    $orderCheck = Db::name('qt_order')->where(['room_id' => $roomId, 'pay_status' => '1'])->find();
                    if (empty($orderCheck)) {
                        $order['order_no'] = ordersn();
                        $order['store_id'] = $this->userInfo['store_id'];
                        $order['room_id'] = $roomId;
                        $order['hand_card_id'] = '';
                        $order['total_num'] = '1';
                        $order['total_price'] = $projectRes['price'];
                        $order['status'] = '1';
                        $order['order_type'] = $orderType;
                        $order['delay'] = 0;
                        $order['time_type'] = '1';
                        $order['created_time'] = time();
                        $orderId = Db::name('qt_order')->insertGetId($order);
                    } else {
                        $orderId = $orderCheck['id'];
                    }
                    //生成订单附表
                    $orderProject = [
                        'name' => $projectRes['name'],
                        'created_order_id' => $this->userInfo['id'],
                        'order_id' => $orderId,
                        'engineer_id' => $engineerId,
                        'project_id' => $getData['project_id'] ?? $find['project_id'],
                        'room_id' => $getData['room_id'] ?? $find['room_id'],
                        'hand_card_id' => '',
                        'order_type' => $orderType,
                        'num' => '1',
                        'price' => $projectRes['price'],
                        'store_id' => $projectRes['store_id'],
                        'creater_room' => $this->userInfo['id'],
                        'created_time' => time(),
                        'sale_id' => $this->userInfo['id'],
                    ];
                    Db::name('qt_order_project')->insert($orderProject);
                    $project = Db::name('qt_order_project')->where('order_id', $orderId)->find();
                    $store = Db::name('qt_store')->where('id', $project['store_id'])->find();
                    $model = new \app\common\model\Order();
                    $result = $model->scheduling($project, '4', $store, $engineerId);
                    if ($result['code'] == '204') {
                        $this->result($result['msg'], '', 204);
                    }
                } catch (Exception $exception) {
                    Db::rollback();
                    return ['code' => 204, 'msg' => '技师排班失败'];
                }
            }
            $update['status'] = '2';
            try {
                Db::startTrans();
                //修改订单状态
                Db::name('qt_room_appointment')->where('id', $getData['id'])->update($update);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('取消失败', '', 204);
            }
            $this->result('确认成功', '', 200);
        }
    }


    /**
     * 预约列表
     */
    public function list_appointment()
    {
        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $data = Db::name('qt_room_appointment')
                ->field('ra.id,ra.time,ra.status,ra.is_call,r.name,u.real_name,p.name as project_name,engineer_id,ra.delay,ra.creater')
                ->alias('ra')
                ->leftJoin('qt_room r', 'ra.room_id = r.id')
                ->leftJoin('qt_users u', 'ra.user_id = u.id')
                ->leftJoin('qt_project p', 'ra.project_id = p.id')
                ->where('ra.status', '1')
                ->where('ra.store_id', $userInfo['store_id'])
                ->select();
            foreach ($data as $key => $value) {
                $data[$key]['engineer'] = Db::name('qt_users')->where('id', $value['engineer_id'])->value('work_number');
                $data[$key]['creater'] = Db::name('qt_users')->where('id', $value['creater'])->value('real_name');
                unset($data[$key]['engineer_id']);
            }
            $this->result('查询成功', $data, 200);
        }
    }


    /**
     * 设置房间颜色
     */
    public function color()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['room_id']) || empty($getData['color'])) {
                $this->result('缺少参数', '', 204);
            }
            try {
                Db::startTrans();
                //修改订单状态
                Db::name('qt_room')->where('id', $getData['room_id'])->update(['color' => $getData['color']]);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('设置失败', '', 204);
            }
            $this->result('设置成功', '', 200);
        }
    }

    /**
     * 更改房间状态
     */
    public function clean()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['room_id']) || !isset($getData['room_id'])) {
                $this->result('缺少参数', '', 204);
            }

            if (empty($getData['status']) || !isset($getData['status'])) {
                $this->result('缺少房间状态', '', 204);
            }
            $roomData = Db::name('qt_room')->where(['id'=>$getData['room_id']])->find();
            if ($getData['status'] == '1') {
                if (isset($getData['user_id']) && !empty($getData['user_id'])) {
                    if(isset($getData['bed_num']) && !empty($getData['bed_num']) && $roomData['clean_rule'] == '2'){
                        $insert['single_commission'] = $roomData['clean_price'];
                        $insert['total_commission'] = $roomData['clean_price'] * $getData['bed_num'];
                    }else{
                        $insert['total_commission'] = $roomData['clean_price'];
                    }
                    $insert['open_time'] = Db::name('qt_room_log')->where(['room_id'=>$getData['room_id']])->order('id desc')->value('created_time');
                    $insert['store_id'] = $this->userInfo['store_id'];
                    $insert['room_id'] = $getData['room_id'];
                    $insert['user_id'] =  $this->userInfo['id'];
                    $insert['clear_user_id'] = $getData['user_id'];
                    $insert['clear_time'] =time();
                    $insert['create_time'] =time();
                    Db::name('qt_room_clear')->insert($insert);
                }
                //查看房间是否有等位
                $waitCount = Db::name('qt_wait')->where(['room_id' => $getData['room_id'], 'status' => '1'])->find();
                if (!empty($waitCount)) {
                    $this->result('房间内有等待，无法取消房间！', '', 204);
                }
                if($roomData['marge'] != ''){
                    if($roomData['marge'] != ''){
                        Db::name('qt_room')->where(['id'=>$getData['room_id']])->update(['marge'=>'','down_time'=>null]);
                    }
                }
            }
            if ($getData['status'] == '6' || $getData['status'] == '7'  || $getData['status'] == '1' || $getData['status'] == '8' || $getData['status'] == '5') {
                //查找房间是否有未结账的账单
                $project = Db::name('qt_order_project')
                    ->where(['room_id' => $getData['room_id'], 'pay_status' => '0','is_change'=>'1','is_delete'=>'2'])
                    ->where('status','<','4')
                    ->whereNotNull('engineer_id')
                    ->where('engineer_id','neq','0')
                    ->find();
                if (!empty($project)) {
                    $this->result('当前房间有未结账项目，请先处理商品结账！', '', 204);
                }
                //查找房间是否有未结账的账单
                $goods = Db::name('qt_product_order_item')
                    ->where(['room_id'=>$getData['room_id'],'pay_status'=>'0','status'=>'1'])
                    ->find();
                if(!empty($goods)){
                    $this->result('当前房间有未结账商品，请先处理商品结账！', '', 204);
                }
            }
            try {
                Db::startTrans();
                //修改订单状态
                Db::name('qt_room')->where('id', $getData['room_id'])->update(['status_id' => $getData['status'], 'down_time' => null]);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('设置失败', '', 204);
            }
            $this->result('设置成功', '', 200);
        }
    }

    /**
     * 获取商品分类
     */
    public function goodsCate()
    {
        if ($this->request->isPost()) {
            $data = Db::name('qt_goods_category')
                ->field('id,name,sort')
                ->where(['store_id' => $this->userInfo['store_id'], 'status' => '1'])
                ->order('sort  asc')
                ->select();
            $this->result('请求成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 获取商品分类
     */
    public function goods()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['category_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $data = Db::name('qt_goods')
                ->field('id,name,price')
                ->where(['goods_category_id' => $getData['category_id']])
                ->select();
            $this->result('请求成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }



    /**
     * 添加商品到购物车
     */
    public function add_cart()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new \app\web\validate\Room();
            if (!$validate->scene('cart')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            if($this->storeInfo['type'] != '1' ){
                if(!isset($getData['hand_card_name']) || empty($getData['hand_card_name'])){
                    $this->result('请填写手牌号', '', 204);
                }
            }
            $orderModel = new ProductOrder();
            $status = $orderModel->createOrder($getData, $this->userInfo);
            if ($status['status'] == true) {
                //插入消息
                $goodsData = json_decode($getData['goods'],true);
                goodsOrderMessage($this->userInfo['store_id'],$goodsData,$getData['room_id']);
                //下单打印小票
                FeiEPrintService::printPc($getData,$this->userInfo);
                $this->result('添加成功', '', 200);
            }else{
                $this->result($status['msg'], '', 204);
            }
        } else {
            $this->result('无效的请求方式', '', 204);

        }
    }


    /**
     * 购物车列表
     */
    public function list_cart()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['room_id'] || !isset($getData['room_id']))) {
                $this->result('缺少房间参数', '', 204);
            }
            if (empty($getData['limit'] || !isset($getData['limit']))) {
                $this->result('缺少房间参数', '', 204);
            }
            $data = Db::name('qt_product_cart')
                ->field('pc.id,pc.product_name,pc.product_price,pc.num,pc.discount,r.name as room_name,hc.name as hand_card_name,pc.created_time')
                ->alias('pc')
                ->leftJoin('qt_hand_card hc', 'hc.id = pc.hand_card_id')
                ->leftJoin('qt_room r', 'r.id = pc.room_id')
                ->where(['pc.room_id' => $getData['room_id']])
                ->order('pc.id desc')
                ->paginate($getData['limit']);
            $this->result('添加成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 删除购物车
     */
    public function del_cart()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['id'] || !isset($getData['id']))) {
                $this->result('缺少购物车信息', '', 204);
            }
            $del = Db::name('qt_product_cart')
                ->where(['id' => $getData['id']])
                ->delete();
            if ($del) {
                $this->result('删除成功', '', 200);
            }
            $this->result('添加失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 添加房间
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new \app\api\validate\Room();
            if (!$validate->scene('add_room')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $getData['created_time'] = time();
            $getData['store_id'] = $this->store_id;
            $uniq_room = Db::name('qt_room')
                ->where('name', $getData['name'])
                ->where('store_id', $this->store_id)
                ->where('is_deleted', CommonConstant::IS_DELETED_NO)
                ->find();
            if (!empty($uniq_room)) {
                $this->result('房间名称已经存在', '', 204);
            }

            $roomId = Db::name('qt_room')->insertGetId($getData);
            if ($getData['bed_num'] != '0') {
                $roomBedData = [];
                for ($i = 1; $i <= $getData['bed_num']; $i++) {
                    $roomBedData[$i]['store_id'] = $this->userInfo['store_id'];
                    $roomBedData[$i]['room_id'] = $roomId;
                    $roomBedData[$i]['name'] = '0' . $i;
                    $roomBedData[$i]['status'] = 1;
                    $roomBedData[$i]['created_time'] = time();
                }
                Db::name('qt_room_bed')->insertAll($roomBedData);
            }
            $this->result('添加成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 编辑房间
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $validate = new \app\api\validate\Room();
            if (!$validate->scene('edit_room')->check($post)) {
                $this->result($validate->getError(), '', 204);
            }
            $uniq_room = Db::name('qt_room')
                ->where('id', '<>', $post['room_id'])
                ->where('store_id', $this->store_id)
                ->where('is_deleted', CommonConstant::IS_DELETED_NO)
                ->where('name', $post['name'])->find();
            if (!empty($uniq_room)) {
                $this->result('房间名称已经存在', '', 204);
            }
            Db::name('qt_room')->where('id', $post['room_id'])->update($post);

            if ($post['bed_num'] != 0) {
                Db::name('qt_room_bed')->where('room_id', $post['room_id'])->delete();
                $bed_data = [];
                for ($i = 1; $i <= $post['bed_num']; $i++) {
                    $bed_data[$i]['store_id'] = $this->store_id;
                    $bed_data[$i]['room_id'] = $post['room_id'];
                    $bed_data[$i]['name'] = '0' . $i;
                    $bed_data[$i]['status'] = 1;
                    $bed_data[$i]['created_time'] = time();
                }
                Db::name('qt_room_bed')->insertAll($bed_data);
            }
            $this->result('操作成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }

    public function delete()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $room_data = Db::name('qt_room')
                ->where('id', $post['room_id'])
                ->where('is_deleted', 2)
                ->find();
            if (empty($room_data)) {
                $this->result('没有找到需要删除的房间', '', 204);
            }
            Db::name('qt_room')
                ->where('id', $post['room_id'])
                ->update(['is_deleted' => CommonConstant::IS_DELETED_YES]);
            $this->result('操作成功', '', 200);
        }
        $this->result('无效的请求', '', 204);

    }

    /**
     * 获取房间详情
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function room_detail()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $room_data = Db::name('qt_room')
                ->where('id', $post['room_id'])
                //->where('is_deleted',2)
                ->find();
            if (empty($room_data)) {
                $this->result('没有找到需要的房间', '', 204);
            }
            if (in_array($room_data['status_id'], ['2', '3', '4', '10'])) {
                $roomRes = Db::name('qt_room_log')
                    ->field('u.real_name,l.created_time')
                    ->alias('l')
                    ->leftJoin('qt_users u', 'u.id = l.user_id')
                    ->where(['l.room_id' => $room_data['id']])
                    ->order('l.id desc')
                    ->find();
                $room_data['open_name'] = $roomRes['real_name'];
                $room_data['open_created_time'] = $roomRes['created_time'];
            } else {
                $room_data['open_name'] = '';
                $room_data['open_created_time'] = '';
            }
            if (!empty($room_data['marge'])) {
                $roomIds = explode(',', $room_data['marge']);
                $roomName = Db::name('qt_room')->whereIn('id', $roomIds)->column('name');
                $room_data['marge_name'] = implode('-', $roomName);
            } else {
                $room_data['marge_name'] = '';
            }
            $room_data['room_book'] = Db::name('qt_room_book')->where(['room_id'=>$post['room_id'],'status'=>'1'])->count();
            $this->result('操作成功', $room_data, 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 获取房间列表
     */
    public function lists()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $limit = !empty($getData['limit']) ? $getData['limit'] : 10;
            $data = Db::name('qt_room')
                ->alias('r')
                ->field('r.id,r.name,rt.name as type_name')
                ->leftJoin('qt_room_type rt', 'rt.id = r.type_id')
                ->where(['r.store_id' => $this->store_id, 'r.is_deleted' => CommonConstant::IS_DELETED_NO])
                ->paginate($limit);
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 转房
     */
    public function transfer()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['old_room_id']) || empty($getData['new_room_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $projectOrderIds = explode(',', $getData['project_order_ids']);
            $goodsOrderIds = explode(',', $getData['goods_order_ids']);
            $oldData = Db::name('qt_order')
                ->where(['room_id' => $getData['old_room_id']])
                ->whereIn('status', ['1', '2', '3'])
                ->order('id desc')
                ->find();
            $oldRoom = Db::name('qt_room')->where('id', $getData['old_room_id'])->find();
            $newRoomStatus = Db::name('qt_room')->where(['id'=>$getData['new_room_id']])->value('status_id');
            if($newRoomStatus == '1'){
                Db::name('qt_room_log')->insert(['room_id'=>$getData['new_room_id'],'user_id'=>$this->userInfo['id'],'created_time'=>time()]);
            }
            if ($getData['all_transfer'] == '1') {
                //更新新房间信息
                try {
                    Db::startTrans();
                    //更新订单房间
                    Db::name('qt_order')->where('id', $oldData['id'])->update(['room_id' => $getData['new_room_id']]);
                    //更新项目房间
                    foreach ($projectOrderIds as $key => $value) {
                        Db::name('qt_order_project')->where(['id' => $value])->update(['room_id' => $getData['new_room_id']]);
                        //获取技师
                        $engineerId = Db::name('qt_order_project')->where(['id' => $value])->value('engineer_id');
                        if(!empty($engineerId)){
                            Db::name('qt_order_queue')->where(['user_id' => $engineerId])->update(['room_id' => $getData['new_room_id']]);
                        }
                    }
                     //更新房间商品
                    foreach ($goodsOrderIds as $key => $value) {
                        Db::name('qt_product_order_item')->where('id', $value)->update(['room_id'=>$getData['new_room_id']]);
                    }
                    //更新产品房间
                    $productOrderId = Db::name('qt_product_order_item')->where('id', $goodsOrderIds[0])->value('order_id');
                    Db::name('qt_product_order')->where(['id' => $productOrderId])->update(['room_id' => $getData['new_room_id']]);
                    //老房间更改为待扫
                    Db::name('qt_room')->where('id', $getData['old_room_id'])->update(['status_id' => '5']);
                    //新房间更新为老房间状态
                    Db::name('qt_room')->where('id', $getData['new_room_id'])->update(['status_id' => $oldRoom['status_id']]);
                    Db::commit();
                } catch (Exception $exception) {
                    Db::rollback();
                    $this->result('转房失败', '', 204);
                }
            } else {
                //判断新房间是否有项目订单
                $newOrderData = Db::name('qt_order')
                    ->where(['room_id' => $getData['new_room_id']])
                    ->whereIn('status', ['1', '2', '3'])
                    ->order('id desc')
                    ->find();
                if (empty($newOrderData)) {
                    //创建订单
                    $order['order_no'] = ordersn();
                    $order['store_id'] = $this->userInfo['store_id'];
                    $order['room_id'] = $getData['new_room_id'];
                    $order['hand_card_id'] = '';
                    $order['total_num'] = $getData['total_order_num'];
                    $order['total_price'] = $getData['total_order_price'];
                    $order['status'] = '1';
                    $order['delay'] = 0;
                    $order['time_type'] = 1;
                    $order['created_time'] = time();
                    $orderId = Db::name('qt_order')->insertGetId($order);
                } else {
                    $orderId = $newOrderData['id'];
                }
                //判断新房间是否有商品订单
                $newGoodsData = Db::name('qt_product_order')
                    ->where(['is_delete'=>'2','is_change'=>'1'])
                    ->where(['room_id' => $getData['new_room_id'], 'order_status' => '1'])
                    ->order('id desc')
                    ->find();
                if (empty($newGoodsData)) {
                    //创建订单
                    $orderInsert = [
                        'order_no' => c_order_sn('2'),
                        'store_id' => $this->userInfo['store_id'],
                        'room_id' => $getData['new_room_id'],
                        'engineer_id' => '',
                        'create_id' => $this->userInfo['id'],
                        'hand_card_id' => '',
                        'total_price' => $getData['total_goods_price'],
                        'content' => '',
                        'order_status' => '1',
                        'create_time' => time(),
                    ];
                    $goodsOrderId = Db::name('qt_product_order')->insertGetId($orderInsert);
                } else {
                    $goodsOrderId = $newGoodsData['id'];
                }
                //更新新房间信息
                try {
                    Db::startTrans();
                    //更新项目房间
                    foreach ($projectOrderIds as $key => $value) {
                        Db::name('qt_order_project')->where(['id' => $value])->update(['room_id' => $getData['new_room_id'], 'order_id' => $orderId]);
                        //获取技师
                        $engineerId = Db::name('qt_order_project')->where(['id' => $value])->value('engineer_id');
                        if(!empty($engineerId)){
                            Db::name('qt_order_queue')->where(['user_id' => $engineerId])->update(['room_id' => $getData['new_room_id']]);
                        }
                    }
                    //更新产品房间
                    foreach ($goodsOrderIds as $key => $value) {
                        Db::name('qt_product_order_item')->where(['id' => $value])->update(['old_room_id' => $getData['old_room_id'], 'order_id' => $goodsOrderId]);
                    }
                    //新房间更新为老房间状态
                    Db::name('qt_room')->where('id', $getData['new_room_id'])->update(['status_id' => $oldRoom['status_id']]);
                    Db::commit();
                } catch (Exception $exception) {
                    Db::rollback();
                    $this->result('转房失败', '', 204);
                }
            }
            $this->result('转房成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 合并房
     */
    public function combined()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['old_room_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $oldRoomIds = explode(',', $getData['old_room_id']);
            $newRoomIds = explode(',', $getData['new_room_id']);
            //合并房间数据
            $marge = array_merge($oldRoomIds, $newRoomIds);
            if (empty($getData['new_room_id'])) {
                //处理多次提交后数值不一致问题
                $oldMarge = Db::name('qt_room')->where('id', $oldRoomIds[0])->value('marge');
                $oldMarge = explode(',', $oldMarge);
                foreach ($oldMarge as $key => $value) {
                    Db::name('qt_room')->where('id', $value)->update(['marge' => '']);
                }
                $this->result('合并房成功', '', 200);
            }
            //处理多次提交后数值不一致问题
            $oldMarge = Db::name('qt_room')->where('id', $oldRoomIds[0])->value('marge');
            $oldMarge = explode(',', $oldMarge);
            $array = array_diff($oldMarge, $marge);
            if(!empty($array)) {
                foreach ($array as $key => $value) {
                    if($value != ""){
                        $select = Db::name('qt_room')
                            ->where("FIND_IN_SET(" . $value . ",marge)")
                            ->select();
                        if (!empty($select)) {
                            foreach ($select as $k => $v) {
                                Db::name('qt_room')->where('id', $v['id'])->update(['marge' => '']);
                            }
                        }
                    }
                }
            }
            foreach ($marge as $key => $value) {
                $update = ['marge' => implode(',', $marge)];
                Db::name('qt_room')->where('id', $value)->update($update);
            }
            $this->result('合并房成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 取消合并房
     */
    public function removeCombined()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['room_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $margeIds = Db::name('qt_room')->where('id', $getData['room_id'])->value('marge');
            if (!empty($margeIds)) {
                //更新所有的房间状态
                $roomIds = explode(',', $margeIds);
                foreach ($roomIds as $key => $value) {
                    Db::name('qt_room')->where('id', $value)->update(['marge' => '']);
                }
            }
            $this->result('取消成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 获取房间列表
     */
    public function engineer_room()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $where = [];
            //房间类型
            if (!empty($getData['type_id'])) {
                $where['r.type_id'] = $getData['type_id'];
            }
            //房间状态
            if (!empty($getData['status_id'])) {
                $where['r.status_id'] = $getData['status_id'];
            }
            //房间状态
            if (!empty($getData['bed_num'])) {
                $where['r.bed_num'] = $getData['bed_num'];
            }
            if (empty($where)) {
                $where = 1;
            }
            $total_member = 0;
            $total_price = 0;
            //原始数据
            $originalData = Db::name('qt_room')
                ->alias('r')
                ->leftJoin('qt_room_type rt', 'rt.id = r.type_id')
                ->leftJoin('qt_room_status rs', 'rs.id = r.status_id')
                ->field('r.id,r.name,rt.name as type_name,rs.name as status_name,r.type_id,rs.color,r.status_id,r.color as room_color,r.bed_num,r.marge,r.down_time,r.content')
                ->where(['r.store_id' => $this->userInfo['store_id'], 'r.is_deleted' => '2'])
                ->where($where)
                ->select();
            foreach ($originalData as $key => $value) {
                if ($value['status_id'] == '2' || $value['status_id'] == '3' || $value['status_id'] == '4' || $value['status_id'] == '10') {
                    $engineer = Db::name('qt_order_queue')
                        ->alias('oq')
                        ->leftJoin('qt_users u', 'oq.user_id = u.id')
                        ->where(['oq.room_id' => $value['id']])
                        ->whereIn('oq.status', ['2', '1','3'])
                        ->column('u.work_number');
                    $engineer = array_unique($engineer);
                    //单个房间项目
                    $project = Db::name('qt_order')
                        ->field('o.id,r.name as room_name,h.name as hand_card_name')
                        ->alias('o')
                        ->leftJoin('qt_room r','r.id = o.room_id')
                        ->leftJoin('qt_hand_card h','h.id = o.hand_card_id')
                        ->where(['room_id'=>$value['id'],'pay_status'=>'1'])
                        ->order('o.id desc')
                        ->find();
                    if(!empty($project)){
                        $projectPrice = Db::name('qt_order_project')
                            ->alias('op')
                            ->leftJoin('qt_order o', 'o.id = op.order_id')
                            ->leftJoin('qt_users u', 'op.engineer_id = u.id')
                            ->where(['o.room_id' => $value['id'],'op.pay_status'=>'0','op.order_id'=>$project['id'],'op.is_delete'=>'2','op.is_change'=> '1',])
                            ->whereIn('op.status', ['2', '1','3'])
                            ->whereNotNull('engineer_id')
                            ->where('engineer_id','neq','0')
                            ->sum('op.price');
                    }else{
                        $projectPrice = 0;
                    }
                    //未结账项目数量
                    $projectPay = Db::name('qt_order_project')
                        ->alias('op')
                        ->leftJoin('qt_order o', 'o.id = op.order_id')
                        ->leftJoin('qt_users u', 'op.engineer_id = u.id')
                        ->where(['o.room_id' => $value['id'], 'op.pay_status' => '0'])
                        ->whereIn('op.status', ['2', '1', '3'])
                        ->whereNotNull('op.engineer_id')
                        ->count();
                    $goodsOrder = Db::name('qt_product_order')
                        ->where(['room_id' => $value['id'], 'pay_status' => '0'])
                        ->order('id desc')
                        ->find();
                    $goodsPrice = Db::name('qt_product_order_item')
                        ->where(['order_id'=>$goodsOrder['id'],'status'=>'1'])
                        ->sum('goods_total_price');
                    //未结算商品数量
                    $goodsPay = Db::name('qt_product_order_item')
                        ->where(['order_id'=> $goodsOrder['id'],'status'=>'1'])
                        ->count();
                    $count = $projectPay + $goodsPay;
                    $price = $projectPrice + $goodsPrice;
                    $total_member += count($engineer);
                    $total_price += $price;
                    $originalData[$key]['price'] = $price;
                    $originalData[$key]['count'] = $count;
                    $originalData[$key]['member'] = count($engineer);
                    foreach ($engineer as $k => $v) {
                        if ($v == null) {
                            unset($engineer[$k]);
                        }
                    }
                    //查找各个技师的起钟时间
                    $engineerIds = Db::name('qt_order_queue')
                        ->where('room_id', $value['id'])
                        ->whereNotNull('start_time')
                        ->whereNull('real_time')
                        ->order('end_time desc')
                        ->column('end_time');
                    //项目的时间
                    $projectTime = Db::name('qt_order_project')
                        ->alias('op')
                        ->leftJoin('qt_project p', 'p.id = op.project_id')
                        ->where(['op.room_id' => $value['id'], 'op.is_change' => '1'])
                        ->whereIn('op.status', ['2', '3', '1'])
                        ->order('op.start_time desc')
                        ->column('p.time');
                    if (empty($engineerIds)) {
                        $originalData[$key]['end_time'] = null;
                    } else {
                        $originalData[$key]['end_time'] = $engineerIds;
                    }
                    //是否有预约
                    $appointment = Db::name('qt_room_appointment')->where(['room_id' => $value['id'], 'status' => '1'])->find();
                    if (empty($appointment)) {
                        $originalData[$key]['appointment'] = 0;//没有预约
                    } else {
                        $originalData[$key]['appointment'] = 1;//有预约
                    }
                    $originalData[$key]['time'] = implode(',', $projectTime);
                    $originalData[$key]['engineer'] = implode(',', $engineer);
                    $originalData[$key]['price'] = $price;
                    $wait = Db::name('qt_wait')->where(['room_id' => $value['id'], 'status' => '1'])->count();
                    $originalData[$key]['wait'] = $wait;
                    if (!empty($value['marge'])) {
                        $roomIds = explode(',', $value['marge']);
                        $roomName = Db::name('qt_room')->whereIn('id', $roomIds)->column('name');
                        $originalData[$key]['marge_name'] = implode('-', $roomName);
                        $originalData[$key]['marge_number'] = count($roomIds);
                    }
                } else {
                    $originalData[$key]['member'] = 0;
                    $originalData[$key]['engineer'] = '';
                    $originalData[$key]['price'] = 0;
                    $originalData[$key]['count'] = 0;
                    $originalData[$key]['wait'] = 0;
                    $originalData[$key]['start_time'] = null;
                    $originalData[$key]['appointment'] = 0;//没有预约
                }
                $originalData[$key]['room_book'] = Db::name('qt_room_book')->where(['room_id' => $value['id'], 'status' => '1'])->count();
            }
            $this->result('查询成功', $originalData, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 房间详情
     */
    public function detail()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['room_id']) || empty($getData['room_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $project = [];
            $product = [];
            $totalProjectMoney = 0;
            $totalGoodsMoney = 0;
            $roomRes = Db::name('qt_room')->where(['id' => $getData['room_id']])->find();
            if (in_array($roomRes['status_id'], ['2', '3', '4','10'])) {
                $order = Db::name('qt_order')->where(['room_id' => $getData['room_id'],'pay_status'=>'1'])->order('id desc')->find();
                $project = Db::name('qt_order_project')
                    ->field('op.id,op.name,op.num,op.price,op.created_time,u.real_name,op.start_time,op.end_time,op.real_end_time,op.engineer_id,op.status,op.order_type,op.pay_status')
                    ->alias('op')
                    ->leftJoin('qt_users u', 'u.id = op.created_order_id')
                    ->where(['op.order_id'=> $order['id'],'op.is_change'=>'1'])
                    ->where('op.engineer_id','neq','0')
                    ->where('op.is_delete',2)
                    ->whereIn('op.status', ['1', '2', '3'])
                    ->whereNotNull('op.engineer_id')
                    ->select();
                if (!empty($project)) {
                    foreach ($project as $key => $value) {
                        $totalProjectMoney += $value['price'];
                        $project[$key]['type'] = '1';
                        $project[$key]['work_number'] = Db::name('qt_users')->where(['id' => $value['engineer_id']])->value('work_number');
                    }
                }
                $order = Db::name('qt_product_order')->where(['room_id' => $getData['room_id'],'pay_status'=>0])->order('id desc')->find();
                $product = Db::name('qt_product_order_item')
                    ->field('id,goods_name as name,goods_total_price as price,goods_num as num,create_time as created_time,pay_status,create_id')
                    ->where(['order_id' => $order['id'],'status'=>'1'])
                    ->select();
                if (!empty($product)) {
                    foreach ($product as $key => $value) {
                        $totalGoodsMoney += $value['price'];
                        $product[$key]['real_name'] = Db::name('qt_users')->where(['id' => $value['create_id']])->value('real_name');
                        $product[$key]['type'] = '2';
                    }
                }
            }
            $data = array_merge($project, $product);
            $result['data'] = $data;
            $result['total_goods_money'] = $totalGoodsMoney;
            $result['total_project_money'] = $totalProjectMoney;
            $this->result('请求成功', $result, 200);
        }
        $this->result('无效的请求方式', '', 204);
    }

    /**
     *取消房间
     */
    public function close()
    {
        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $getData = $this->request->post();
            if (empty($getData['room_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $data = Db::name('qt_room')
                ->field('id,name,status_id')
                ->where(['id' => $getData['room_id'], 'store_id' => $userInfo['store_id'], 'status_id' => '2'])
                ->find();
            if (empty($data) || $data['status_id'] != '2') {
                $this->result('房间状态有问题', '', 204);
            }
            try {
                Db::startTrans();
                //修改房间状态
                Db::name('qt_room')->where(['id' => $getData['room_id']])->update(['status_id' => '1']);
                $roomLog['room_id'] = $getData['room_id'];
                $roomLog['user_id'] = $userInfo['id'];
                $roomLog['status'] = '1';
                $roomLog['created_time'] = time();
                Db::name('qt_room_log')->insert($roomLog);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('取消失败', '', 204);
            }
            $this->result('取消成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 获取用户房间单据
     */
    public function bill()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            //结账筛选
            $where[] = ['op.pay_status', '=', $getData['pay_status']];
            //项目
            $projectRes = Db::name('qt_order_project')
                ->alias('op')
                ->field('op.id as product_order_id,op.name as goods_name,op.old_name as old_goods_name,op.room_id,
                op.order_type,op.created_time,op.engineer_id,op.start_time,op.end_time,op.old_card_id,op.hand_card_id,op.old_card_id,
                op.old_room_id,op.is_change,op.status,op.is_add,op.created_order_id as create_id,op.commission,op.receiver,op.sale_id,
                r.name as room_name,h.name as hand_card_name,op.price'
                )
                ->leftJoin('qt_order o', 'o.id=op.order_id')
                ->leftJoin('qt_room r', 'r.id = o.room_id')
                ->leftJoin('qt_hand_card h', 'h.id = o.hand_card_id')
                //->whereNotIn('op.status', ['4', '5'])
                ->where(['op.store_id' => $this->store_id])
                //->whereNotNull('op.engineer_id')
                ->where($where)
                ->select();
            foreach ($projectRes as $key => $value) {
                $projectRes[$key]['work_number'] = Db::name('qt_users')->where('id', $value['engineer_id'])->value('work_number');//技师
                $projectRes[$key]['sale_name'] = Db::name('qt_users')->where('id', $value['sale_id'])->value('real_name');//销售人
                //$projectRes[$key]['room_name'] = $project['room_name'];
                //$projectRes[$key]['hand_card_name'] = Db::name('qt_hand_card')->where('id',$value['hand_card_id'])->value('name');
                $projectRes[$key]['old_card_name'] = Db::name('qt_hand_card')->where('id', $value['old_card_id'])->value('name');
                $projectRes[$key]['old_room'] = Db::name('qt_room')->where('id', $value['old_room_id'])->value('name');//原房间
                $projectRes[$key]['create_name'] = Db::name('qt_users')->where('id', $value['create_id'])->value('real_name');//下单人
                $projectRes[$key]['type'] = '1';//下单人
                $projectRes[$key]['goods_num'] = '1';//数量
                $projectRes[$key]['total_price'] = $value['price'];//金额
                $projectRes[$key]['open_room_time'] = Db::name('qt_room_log')->where('room_id', $value['room_id'])->order('id desc')->value('created_time');;//开房时间
            }

            //商品
            $productRes = Db::name('qt_product_order_item')->alias('op')
                ->field('op.id as product_order_id,op.goods_name,op.old_goods_name,op.old_goods_name,
                op.goods_num,op.create_time,op.create_id,op.sale_id,op.old_room_id,op.goods_total_price,
                op.commission,op.receiver,r.name as room_name,h.name as hand_card_name,po.engineer_id,r.id as room_id')
                ->leftJoin('qt_product_order po', 'po.id=op.order_id')
                ->leftJoin('qt_room r', 'r.id = po.room_id')
                ->leftJoin('qt_hand_card h', 'h.id =po.hand_card_id')
                ->where($where)
                ->select();
            foreach ($productRes as $key => $value) {
                $productRes[$key]['engineer_name'] = '';//提成
                $productRes[$key]['sale_name'] = Db::name('qt_users')->where('id', $value['sale_id'])->value('real_name');//销售人
                $productRes[$key]['create_name'] = Db::name('qt_users')->where('id', $value['create_id'])->value('real_name');//提成
                $productRes[$key]['old_card_name'] = '';
                $productRes[$key]['status'] = 0;
                $productRes[$key]['is_change'] = '1';
                $productRes[$key]['is_add_work'] = 0;
                $productRes[$key]['order_type'] = '';
                $productRes[$key]['start_time'] = null;
                $productRes[$key]['end_time'] = null;
                $productRes[$key]['old_room'] = Db::name('qt_room')->where('id', $value['old_room_id'])->value('name');//原房间
                $productRes[$key]['type'] = '2';//商品
                $productRes[$key]['total_price'] = $value['goods_total_price'];//商品
                $productRes[$key]['open_room_time'] = Db::name('qt_room_log')->where('room_id', $value['room_id'])->order('id desc')->value('created_time');;//开房时间
            }
            $data = array_merge($projectRes, $productRes);
            $this->result('请求成功', $data, 200);
        } else {
            $this->result('无效的请求', '', 204);

        }

    }


    /**
     * 会做当前项目的技师
     */
    public function get_use_project()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['project_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $storeId = Db::name('qt_project')->where(['id' => $getData['project_id']])->value('store_id');
            $data = Db::name('qt_user_project')
                ->field('p.id as project_id,u.real_name,u.avatar,u.work_number,u.id as user_id')
                ->alias('p')
                ->leftJoin('qt_users u', 'u.id = p.engineer_id')
                ->where('p.project_id', $getData['project_id'])
                ->where(['u.work_status' => '1', 'u.status' => '0', 'u.store_id' => $storeId])
                ->select();
            foreach ($data as $key => $value) {
                $data[$key]['avatar'] = get_img_path($value['avatar']);
                //技师上钟数量
                $data[$key]['clock_number'] = Db::name('qt_order_project')->where(['engineer_id' => $value['user_id'], 'status' => '3'])->count();
                //技师好评
                $data[$key]['evaluate_number'] = 100;
            }
            $this->result('查询成功', $data, 200);

        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 会做当前技师会做的项目
     */
    public function get_project()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!empty($getData['engineer_id'])) {
                $data =  Db::name('qt_project')
                    ->field('up.project_id,p.name as project_name')
                    ->alias('p')
                    ->leftJoin('qt_user_project up', 'up.project_id = p.id')
                    ->where(['up.engineer_id'=> $getData['engineer_id'],'p.status'=>'1'])
                    ->select();
            }else{
                $data =  Db::name('qt_project')
                    ->field('id as project_id,name as project_name')
                    ->where(['store_id'=>$this->userInfo['store_id'],'status'=>'1'])
                    ->select();
            }
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 获取正在使用中的房间列表
     */
    public function room_use()
    {
        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $data = Db::name('qt_room')
                ->alias('r')
                ->leftJoin('qt_room_status s', 's.id = r.status_id')
                ->field('r.id,r.name,r.status_id,s.name as status_name')
                ->where(['r.store_id' => $userInfo['store_id']])
                ->whereIn('r.status_id', ['2', '3', '4', '10'])
                ->order('r.id asc')
                ->select();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 获取当前在线的男女技师数量
     */
    public function get_user_line()
    {
        if ($this->request->isPost()) {
            $data['man'] = Db::name('qt_order_queue')->alias('oq')
                ->leftJoin('qt_users u', 'u.id = oq.id')
                ->where(['u.sex' => '1', 'u.status' => '0', 'u.role' => '3'])
                ->count();
            $data['girl'] = Db::name('qt_order_queue')->alias('oq')
                ->leftJoin('qt_users u', 'u.id = oq.id')
                ->where(['u.sex' => '2', 'u.status' => '0', 'u.role' => '3'])
                ->count();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 修改房间预约（保存）
     */
    public function save_appointment()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['id'])) {
                $this->result('缺少预约信息', '', 204);
            }
            $data = Db::name('qt_room_appointment')->where('id', $getData['id'])->find();
            if(empty($data)){
                $this->result('缺少预约信息', '', 204);
            }
            if(!empty($getData['engineer_id'])){
                $userStatus = Db::name('qt_users')->where('id', $getData['engineer_id'])->value('work_status');
                if($userStatus == '1' || $userStatus == '3'){
                    Db::name('qt_users')->where('id', $getData['engineer_id'])->update(['work_status'=>'3']);
                }
            }
            if($getData['room_id'] != $data['room_id']){
                //查找老房间状态
                $oldRoomStatus = Db::name('qt_room')->where(['id'=>$data['room_id']])->value('status_id');
                //只有预约房间状态改成空闲
                if($oldRoomStatus == '9'){
                    Db::name('qt_room')->where(['id'=>$data['room_id']])->update(['status_id'=>'1']);
                }
                $newRoomStatus = Db::name('qt_room')->where(['id'=>$getData['room_id']])->value('status_id');
                if($newRoomStatus == '1'){
                    Db::name('qt_room')->where(['id'=>$getData['room_id']])->update(['status_id'=>'9']);
                }
            }
            $getData['time'] = strtotime($getData['time']);
            try {
                Db::startTrans();
                //修改订单状态
                Db::name('qt_room_appointment')->where('id',$getData['id'])->update($getData);
                Db::name('qt_room')->where('id', $getData['room_id'])->update(['status_id' => '9']);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('预约失败', '', 204);
            }
            $this->result('修改成功', '', 200);
        }
    }

    /**
     * 修改房间预约
     */
    public function edit_appointment()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['id'])) {
                $this->result('缺少预约信息', '', 204);
            }
            $data = Db::name('qt_room_appointment')
                ->field('ra.*,r.name as room_name,p.name as project_name,u.work_number')
                ->alias('ra')
                ->leftJoin('qt_room r','r.id = ra.room_id')
                ->leftJoin('qt_project p','p.id = ra.project_id')
                ->leftJoin('qt_users u','u.id = ra.engineer_id')
                ->where('ra.id', $getData['id'])
                ->find();
            $this->result('查询成功', $data, 200);
        }
    }

    /**
     * 门店二维码
     */
    public function store_code()
    {
        if ($this->request->isPost()) {
            $imageName = strtotime(date('Y-m-d')) . '-' . $this->userInfo['store_id'] . '.png';
            $storeName = Db::name('qt_store')->where('id',$this->userInfo['store_id'])->value('name');
            $image = create_ewm(config('app.site_url').'/h5/#/?store_id=' . $this->userInfo['store_id'].'&store_name='.$storeName, 'uploads/qrcode/', $imageName, 10);
            $result = config('app.site_url') . '/uploads/qrcode/' . $image;
            $this->result('查询成功', $result, 200);

        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 添加商品分类
     */
    public function goodsCateAdd()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['sort']) || empty($getData['name']) ){
                $this->result('缺少参数', '', 204);
            }
            $getData['create_time'] = time();
            $getData['store_id'] = $this->userInfo['store_id'];
            $find = Db::name('qt_goods_category')->where(['store_id'=>$this->userInfo['store_id'],'name'=>$getData['name']])->find();
            if(!empty($find)){
                $this->result('商品分类已经存在', '', 204);
            }
            Db::name('qt_goods_category')->insert($getData);
            $this->result('添加成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 编辑商品分类
     */
    public function goodsCateEdit()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['sort']) || empty($getData['name'])  || empty($getData['id']) ){
                $this->result('缺少参数', '', 204);
            }
            Db::name('qt_goods_category')->where(['id'=>$getData['id']])->update($getData);
            $this->result('修改成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 删除商品分类
     */
    public function goodsCateDel()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['id'])){
                $this->result('缺少参数', '', 204);
            }
            $goods = Db::name('qt_goods')->where('goods_category_id',$getData['id'])->find();
            if(!empty($goods)){
                $this->result('商品分类下还存在商品,无法删除', '', 204);
            }
            Db::name('qt_goods_category')->where(['id'=>$getData['id']])->update(['status'=>'2']);
            $this->result('删除成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 获取房间净房规则
     */
    public function clean_rule(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['room_id'])) {
                $this->result('请选择房间号', '', 204);
            }
            $data = Db::name('qt_room')->field('clean_rule,clean_price,bed_num')->where(['id'=>$getData['room_id']])->find();
            $this->result('查询成功', $data, 200);
        }
    }

}
